package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"lucky_srv/models"
	"lucky_srv/pkg"

	"lucky_srv/internal/svc"
	"lucky_srv/lucky"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *lucky.CreateOrderRequest) (*lucky.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	var g models.Goods
	var o models.Order

	if err = u.GetUserById(in.UserId); err != nil {
		return nil, errors.New("用户信息获取失败")
	}
	if u.ID == 0 {
		return nil, errors.New("该用户不存在")
	}
	if err = g.GetGoodsById(in.GoodsId); err != nil {
		return nil, errors.New("饮品信息获取")
	}
	if g.ID == 0 {
		return nil, errors.New("该饮品不存在")
	}

	if g.Stock < in.Num {
		logx.Error("饮品库存不足")
		return nil, errors.New("饮品库存不足")
	}

	o.UserID = in.UserId
	o.GoodsId = in.GoodsId
	o.OrderSn = uuid.NewString()
	o.Num = in.Num
	o.Total = g.Price*float64(in.Num) + 5
	o.Ads = in.Ads
	o.PayType = in.PayType

	if err = o.Create(); err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	amount := fmt.Sprintf("%.2f", o.Total)
	payUrl := pkg.Alipay(amount, o.OrderSn)

	g.Stock -= in.Num
	models.DB.Where("id=?", in.GoodsId).Update("stock", g.Stock)

	return &lucky.CreateOrderResponse{
		OrderSn: o.OrderSn,
		PayUrl:  payUrl,
	}, nil
}
